scala类转换为json 您所在的位置:网站首页 scala some转string scala类转换为json

scala类转换为json

2023-09-18 04:36| 来源: 网络整理| 查看: 265

scala类转换为json 一,依赖二,java实例三,scala实例四,原因 使用fastjson将java 实体类转换为json很方便,但是直接用在普通的Scala实体类上生成的json是空的"{}",需要使用scala.beans.BeanProperty注解修饰一下scala类字段。

一,依赖 8 8 1.2.54 com.alibaba fastjson ${fastjson.version} 二,java实例 public class JavaUser { private String userName; private String userSex; private int id; public JavaUser(String userName,String userSex,int id){ this.userName=userName; this.userSex=userSex; this.id=id; } public String getUserName() { return userName; } public String getUserSex() { return userSex; } } import com.alibaba.fastjson.*; public class JavaTest { public static void main(String[] args) { System.out.println(JSON.toJSONString(new JavaUser("zhangsan","man",1))); } }

在这里插入图片描述 没有定义getter的字段,不会输出到json中。(public 修饰的字段可以)

private int id; 三,scala实例 import scala.beans.BeanProperty class ScalaUser(@BeanProperty val userName:String,@BeanProperty val userSex:String,_id:Int) { val id:Int=_id } import com.alibaba.fastjson.JSON object ScalaTest { def main(args: Array[String]): Unit = { println(JSON.toJSONString(new ScalaUser("lisi", "woman",2),JSON.DEFAULT_GENERATE_FEATURE)) } }

在这里插入图片描述 使用@BeanProperty修饰的类成员会输出到json中。

四,原因

Scala中代码 var类型字段=private变量+getter+setter; val类型字段=private变量+getter; 但是命名方式与java不同,getter为字段名,setter为**字段名_()**的形式,与fastjson要求的命名方式不一致。BeanProperty则能提供java风格的getter和setter。

package scala.beans /** When attached to a field, this annotation adds a setter and a getter * method following the Java Bean convention. For example: * {{{ * @BeanProperty * var status = "" * }}} * adds the following methods to the class: * {{{ * def setStatus(s: String) { this.status = s } * def getStatus: String = this.status * }}} * For fields of type `Boolean`, if you need a getter named `isStatus`, * use the `scala.beans.BooleanBeanProperty` annotation instead. */ @scala.annotation.meta.field class BeanProperty extends scala.annotation.StaticAnnotation


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有